package com.block.sms.service.send;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplate;
import com.block.sms.dto.SmsBalanceDTO;
import com.block.sms.dto.SmsResultDTO;
import com.block.sms.service.ISmsSendService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * http://39.108.130.4:8001/sms/api/sendMessageOne
 *
 * 网关地址：http://39.108.130.4:8001/sms
 * 帐号：xhrg02
 * 密码：thq6PcAM3fhb
 * 绑定IP：
 */
@Service
public class DingShiSmsSendServiceImpl implements ISmsSendService {

    private static final Logger log = LogFactory.getCommLog();


    @Override
    public SmsResultDTO sendSms(String mobile, String outId, SmsTemplate smsTemplate, SmsConfigInfo smsConfigInfo, JSONObject paramObject) {

        SmsResultDTO  resultDTO = new SmsResultDTO();
        try {
            HttpRequest httpRequest = HttpUtil.createPost(smsConfigInfo.getUrl());

            String username = smsConfigInfo.getAccount();
//            String content = StrUtil.format(smsTemplate.getTemplateContext(), paramArr.stream().toArray());
            String content = smsTemplate.getTemplateContext();
            //创建一个json数组
            JSONArray jsonArray = new JSONArray();
            //创建一个json对象
            JSONObject jsonObject = new JSONObject();
            //把json对象放入json数组中
            jsonObject.put("phone", mobile);
            jsonObject.put("content", content);

            jsonArray.add(jsonObject);

            Long timestamp = System.currentTimeMillis();// spread SPREAD

            // MD5(userName + content + timestamp + MD5(password))
            //stringBuilder字符串进行拼接
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder append = stringBuilder.append(username)
                    .append(timestamp)
                    .append(SecureUtil.md5(smsConfigInfo.getSecret()).toLowerCase(Locale.ROOT));

            String sign = SecureUtil.md5(append.toString()).toLowerCase(Locale.ROOT);
            String sendTime = LocalDateUtil.getNowDateStrByTotalDataTime();

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("userName", username);
            paramMap.put("messageList", jsonArray);
            paramMap.put("timestamp", timestamp);
            paramMap.put("sign", sign);
            paramMap.put("sendTime", sendTime);

            httpRequest.body(JSON.toJSONString(paramMap));

            String bodyResult = httpRequest.execute().body();
            log.info("【鼎石短信服务】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), bodyResult);

            JSONObject resultJson = JSON.parseObject(bodyResult);
            String result = resultJson.getString("result");// 【任信花】尊敬的用户，您的验证码214350如非本人操作，请忽略此短信。

            resultDTO.setData(bodyResult);
            if (StrUtil.equals("0", result)){
                resultDTO.setCode(AppRspCodeConstant.SUCCESS);
                resultDTO.setHttpStatus(result);
                resultDTO.setRequestId(outId);
                resultDTO.setMessage(bodyResult);
                return resultDTO;
            }
            resultDTO.setMessage(bodyResult);
        } catch (Exception exception) {
            log.error(String.format("【大汉三通短信服务】发送发生异常【mobile】%s【code】%s", mobile, paramObject.toJSONString()), exception);
        }
        resultDTO.setCode(AppRspCodeConstant.OPERATION_FAILURE);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

    public static void main(String[] args) {

        StringBuilder stringBuilder = new StringBuilder();
        StringBuilder append = stringBuilder.append("test")
                .append("测试内容")
                .append("1596254400000")
                .append(SecureUtil.md5("123").toLowerCase(Locale.ROOT));

        System.out.println(append);
        System.out.println(SecureUtil.md5(append.toString()).toLowerCase(Locale.ROOT));

    }

}
